/*
 * @Author: xiaosihan
 * @Date: 2025-10-25 10:00:00
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-11-03 17:42:37
 */
import express from "express";
import database from "../database";
import ServiceBase from "./ServiceBase";
import { Op } from 'sequelize';
import OSS from "ali-oss";
import { isEmpty } from "lodash";

// 配置OSS客户端
const oss = new OSS({
    region: 'oss-cn-shanghai',
    accessKeyId: process.env.accessKeyId || "",
    accessKeySecret: process.env.accessKeySecret || "",
    bucket: 'www-3dkeshihua',
});

// 我的图片服务
export default class MyImgService extends ServiceBase {

    constructor(req: express.Request = {} as express.Request, res: express.Response = {} as express.Response) {
        super(req, res);
    }

    // 重排所有图片顺序
    reorderMyImages = async () => {
        await database.sequelize.transaction(async (transaction) => {
            // 初始化排序变量
            await database.sequelize.query(
                'SET @new_order = 0;',
                { transaction }
            );

            // 使用一条SQL语句完成所有记录的order字段重排
            await database.sequelize.query(
                'UPDATE myImg ' +
                'SET `order` = (@new_order := @new_order + 1) ' +
                'ORDER BY `order` ASC',
                {
                    type: 'UPDATE',
                    transaction
                }
            );
        });
    };

    // 获取我的图片列表
    get_my_img_list = async (params: Record<string, any>) => {
        // 参数验证
        this.verifyParams(['page', 'pageSize']);
        const page = parseInt(params.page as string) || 1;
        const pageSize = parseInt(params.pageSize as string) || 10;
        const search = params.search as string;
        const offset = (page - 1) * pageSize;

        // 构建查询条件
        const whereCondition: any = {};
        if (search) {
            whereCondition[Op.or] = [
                { name: { [Op.like]: `%${search}%` } },
                { description: { [Op.like]: `%${search}%` } }
            ];
        }

        // 获取排序参数
        const sortField = params.sortField as string || 'order';
        const sortOrder = params.sortOrder as string || 'ASC';

        // 将前端的排序方向转换为SQL兼容的格式
        let sqlSortOrder = 'ASC';
        if (sortOrder.toUpperCase() === 'DESCEND') {
            sqlSortOrder = 'DESC';
        } else if (sortOrder.toUpperCase() === 'ASCEND') {
            sqlSortOrder = 'ASC';
        }

        // 查询数据并计算总数
        const [data, total] = await Promise.all([
            database.myImg.findAll({
                where: whereCondition,
                offset,
                limit: pageSize,
                order: [[sortField, sqlSortOrder]]
            }),
            database.myImg.count({ where: whereCondition })
        ]);

        return {
            data: data.map(item => item.dataValues),
            page: page,
            pageSize: pageSize,
            total: total
        };
    };

    // 更新我的图片
    write_my_img = async (params: Record<string, any>) => {
        // 参数验证
        const id = parseInt(params.id as string);
        const name = params.name;
        const description = params.description;
        const order = params.order !== undefined ? parseFloat(params.order as string) : undefined;

        // 检查参数有效性
        if (isEmpty(id)) {
            await database.myImg.create(params);
            // 自动重排所有图片顺序
            await this.reorderMyImages();
            return "保存成功";
        }

        // 查找图片
        const myImg = await database.myImg.findByPk(id);
        if (!myImg) {
            throw new Error('未找到指定的图片');
        }

        // 构建更新对象
        const updateData: any = {
            updatedAt: new Date()
        };

        if (name !== undefined) updateData.name = name;
        if (description !== undefined) updateData.description = description;

        // 根据用户要求，如果order值比原来的小就减小0.5，如果比原来的大就增加0.5
        if (order !== undefined) {
            const originalOrder = myImg.order || 0;
            if (order < originalOrder) {
                updateData.order = order - 0.5;
            } else if (order > originalOrder) {
                updateData.order = order + 0.5;
            } else {
                // 如果order值与原值相同，则不做调整
                updateData.order = order;
            }
        }

        // 更新图片信息
        await myImg.update(updateData);

        // 自动重排所有图片顺序
        await this.reorderMyImages();

        return "更新成功";
    };

    // 删除图片
    del_my_img = async (params: { id: number }) => {
        // 参数验证
        this.verifyParams(['id']);
        const { id } = params;
        // 查找图片
        const myImg = await database.myImg.findByPk(id);
        if (!myImg) {
            throw new Error('未找到指定的图片');
        }
        // 从OSS删除图片
        try {
            const url = myImg.url;
            // 提取OSS路径（从URL中移除域名部分）
            const ossPath = url.replace('http://www-3dkeshihua.oss-cn-shanghai.aliyuncs.com/', '');
            await oss.delete(ossPath);
        } catch (error) {
            console.error('从OSS删除图片失败:', error);
            // 即使OSS删除失败，我们仍然从数据库删除记录
        }
        // 从数据库删除记录
        await myImg.destroy();
        // 自动重排所有图片顺序
        await this.reorderMyImages();
        return "删除成功";
    };

}